package com.kedacom.ctsp.authz.access;

import com.alibaba.fastjson.JSONObject;
import com.kedacom.ctsp.authz.entity.Authentication;
import com.kedacom.ctsp.lang.ClassUtil;
import com.kedacom.ctsp.web.entity.RecordableBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author sunchenjie
 * @date 2017/11/29 0029
 */
public abstract class RecordableBeanHandlerAdaptor<E extends RecordableBean> implements RecordableBeanHandler {

    private Class<E> entityClass;
    private Logger logger = LoggerFactory.getLogger(getClass());

    public RecordableBeanHandlerAdaptor() {
        this.entityClass = (Class<E>) ClassUtil.getGenericType(this.getClass(), 0);
    }

    @Override
    public void handle(RecordableBean entity, Authentication auth) {
        if (entity == null) {
            return;
        }
        if (accept(entity)) {
            try {
                handleSilently((E) entity, auth);
            } catch (Exception e) {
                logger.error(String.format("RecordableBeanHandler exception, entity:[%s], auth:[%s] ", JSONObject.toJSONString(entity), auth.toString()));
            }
        }
    }

    protected abstract void handleSilently(E entity, Authentication authentication);

    protected boolean accept(RecordableBean entity) {
        return entityClass.isAssignableFrom(entity.getClass());
    }

}
